const myPromiseAll = (promises) => {
  return new Promise((resolve, reject) => {
    if (!Array.isArray(promises)) throw new Error("非法参数");

    const n = promises.length;

    if (n === 0) resolve([]);

    let cnt = 0;

    let resultList = Array.from({ length: n }, () => null);

    for (let i = 0; i < n; i++) {
      const pms = promises[i];
      Promise.resolve(pms)
        .then((res) => {
          resultList[i] = res;
          cnt++;

          if (cnt === n) resolve(resultList);
        })
        .catch((err) => {
          reject(err);
        });
    }
  });
};

// 测试用例
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(2);
const p3 = Promise.resolve(3);

// 测试成功情况
myPromiseAll([p1, p2, p3]).then((results) => {
  console.log("成功:", results); // [1, 2, 3]
});

// 测试失败情况
const p4 = Promise.resolve(4);
const p5 = Promise.reject("错误发生");

myPromiseAll([p4, p5])
  .then((results) => {
    console.log(results);
  })
  .catch((error) => {
    console.log("失败:", error); // '错误发生'
  });

// 测试空数组
myPromiseAll([]).then((results) => {
  console.log("空数组:", results); // []
});
